import 'package:cult/function/utils/my_common.dart';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'landing_page_controller.dart';
import '../../../function/model/post_model.dart';
import '../../../function/widgets/animated_like_button.dart';

/// 首页组件
/// 使用非常规命名避免标准模式
class LandingPage extends GetView<LandingPageController> {
  const LandingPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/home_bg.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 顶部轮播图区域
                _buildTopCarouselSection(context),

                // 功能按钮区域
                _buildFunctionButtonsSection(context),

                // Today's Picks 标题
                _buildTodaysPicksTitle(context),

                // 帖子列表区域
                _buildPostsListSection(context),

                SizedBox(height: 120.h),
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建顶部轮播图区域
  Widget _buildTopCarouselSection(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Top Picks 标题
        Text('Top Picks')
            .fontSize(24.sp)
            .fontFamily(
              GoogleFonts.berkshireSwash(
                fontWeight: FontWeight.w400,
              ).fontFamily,
            )
            .textColor(MyCommonUtils.white)
            .padding(left: 16.w, top: 10.h, bottom: 20.h),

        // 轮播图
        SizedBox(
          width: double.infinity,
          height: 198.h, // 固定高度
          child: CarouselSlider(
            options: CarouselOptions(
              viewportFraction: 0.75, // 显示70%的宽度，让左右两边可见
              enlargeCenterPage: true, // 放大中心页面
              autoPlay: true, // 自动播放
              autoPlayInterval: Duration(seconds: 3), // 自动播放间隔
              autoPlayAnimationDuration: Duration(milliseconds: 800),
              autoPlayCurve: Curves.fastOutSlowIn,
              pauseAutoPlayOnTouch: true,
              pauseAutoPlayOnManualNavigate: true,
              enableInfiniteScroll: true,
              reverse: false,
              onPageChanged: (index, reason) {
                controller.changeCarouselPage(index);
              },
            ),
            items:
                [0, 1, 2].map((index) {
                  return _buildCarouselItem(context, index);
                }).toList(),
          ),
        ),
      ],
    );
  }

  /// 构建轮播图单个项目
  Widget _buildCarouselItem(BuildContext context, int index) {
    final images = [
      'assets/images/scroll1.png',
      'assets/images/scroll2.png',
      'assets/images/scroll3.png',
    ];

    // 映射scroll图片到post ID
    final postIds = ['1', '2', '3'];
    final postId = postIds[index];

    return GestureDetector(
      onTap: () {
        // 跳转到对应的帖子详情页
        Get.toNamed('/post-detail', arguments: {'postId': postId});
      },
      child: AspectRatio(
        aspectRatio: 280 / 198,
        child: Hero(
          tag: 'carousel_image_$postId',
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(images[index]),
                fit: BoxFit.fill,
              ),
            ),
          ),
        ),
      ),
    );
  }

  /// 构建功能按钮区域
  Widget _buildFunctionButtonsSection(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 20.h),
      child: Row(
        children: [
          // Growth Tracking 按钮
          Expanded(
            child: _buildFunctionButton(
              context,
              'assets/images/growth_tracking.png',
            ),
          ),

          SizedBox(width: 12.w),

          // Plant Science 按钮
          Expanded(
            child: _buildFunctionButton(
              context,
              'assets/images/plant_science.png',
            ),
          ),
        ],
      ),
    );
  }

  /// 构建功能按钮
  Widget _buildFunctionButton(BuildContext context, String imagePath) {
    return Container(
      width: 171.w,
      height: 131.h,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12.r),
        image: DecorationImage(image: AssetImage(imagePath), fit: BoxFit.fill),
      ),
    ).inkWell(
      onTap: () {
        if (imagePath.contains('plant_science')) {
          // 跳转到植物百科页面
          Get.toNamed('/plant-encyclopedia');
        } else if (imagePath.contains('growth_tracking')) {
          // 跳转到成长记录页面
          Get.toNamed('/growth-tracking');
        }
        // 其他按钮的点击事件可以在这里添加
      },
    );
  }

  /// 构建 Today's Picks 标题
  Widget _buildTodaysPicksTitle(BuildContext context) {
    return Text('Today\'s Picks')
        .fontSize(24.sp)
        .fontFamily(
          GoogleFonts.berkshireSwash(fontWeight: FontWeight.w400).fontFamily,
        )
        .textColor(MyCommonUtils.white)
        .padding(left: 16.w, bottom: 0.h);
  }

  /// 构建帖子列表区域
  Widget _buildPostsListSection(BuildContext context) {
    return Obx(() {
      final imagePosts = controller.getImagePosts();

      return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: imagePosts.length,
        itemBuilder: (context, index) {
          final post = imagePosts[index];
          return _buildAnimatedPostItem(context, post, index);
        },
      );
    });
  }

  /// 构建带动画效果的帖子项目
  Widget _buildAnimatedPostItem(
    BuildContext context,
    PostModel post,
    int index,
  ) {
    return TweenAnimationBuilder<double>(
      duration: Duration(milliseconds: 400 + (index * 150)),
      tween: Tween(begin: 0.0, end: 1.0),
      curve: Curves.easeOutCubic,
      builder: (context, value, child) {
        return Transform.translate(
          offset: Offset(0, 30 * (1 - value)),
          child: Opacity(
            opacity: value,
            child: Transform.scale(
              scale: 0.8 + (0.2 * value),
              child: _buildPostItem(context, post),
            ),
          ),
        );
      },
    );
  }

  /// 构建帖子单个项目
  Widget _buildPostItem(BuildContext context, PostModel post) {
    // 获取帖子作者信息
    final author = controller.getUserById(post.userId);
    final authorSignature =
        author?.signature ?? 'Watch green, log every scene.';
    final authorNickname = author?.nickname ?? 'User';
    final authorAvatar = author?.avatar ?? 'assets/images/avatar1.png';

    // 获取评论数
    final commentCount = controller.getPostCommentCount(post.id);

    return GestureDetector(
      onTap: () {
        // 跳转到帖子详情页
        Get.toNamed('/post-detail', arguments: post);
      },
      child: Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
        child: AspectRatio(
          aspectRatio: 358 / 188,
          child: Container(
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(12.r),
              image: DecorationImage(
                image: AssetImage('assets/images/pick_card_bg.png'),
                fit: BoxFit.fill,
              ),
            ),
            child: Stack(
              children: [
                Container(
                  width: double.infinity,
                  height: 40.h,
                  decoration: BoxDecoration(color: Colors.transparent),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        height: 30.h,
                        constraints: BoxConstraints(maxWidth: 250.w),
                        padding: EdgeInsets.symmetric(horizontal: 10.w),
                        decoration: BoxDecoration(
                          color: MyCommonUtils.orange,
                          borderRadius: BorderRadius.circular(100.r),
                        ),
                        child: Center(
                          child: Text(
                            authorSignature,
                            style: TextStyle(
                              fontSize: 13.sp,
                              color: Colors.white,
                              fontWeight: FontWeight.w700,
                            ),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ),

                      Spacer(),

                      Obx(() {
                        // 检查用户是否已登录，未登录用户始终显示未点赞状态
                        final isLoggedIn = controller.userState.isLoggedIn;
                        final isLiked =
                            isLoggedIn
                                ? controller.likeState.isPostLiked(post.id)
                                : false;
                        return AnimatedLikeButton(
                          isLiked: isLiked,
                          onTap: () => controller.togglePostLike(post.id),
                          size: 30.w,
                        );
                      }),
                    ],
                  ),
                ),

                // 帖子内容
                Padding(
                  padding: EdgeInsets.only(top: 38.h, left: 8.w),
                  child: Row(
                    children: [
                      // 帖子图片
                      Hero(
                        tag: 'post_image_${post.id}',
                        child: Container(
                          width: 208.w,
                          height: 138.h,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(16.r),
                            image: DecorationImage(
                              image: AssetImage(post.resourcePath),
                              fit: BoxFit.cover,
                            ),
                          ),
                        ),
                      ),

                      SizedBox(width: 12.w),

                      // 帖子详情
                      Expanded(
                        child: Padding(
                          padding: EdgeInsets.only(right: 10.w),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(height: 44.h),

                              // 标题
                              Text(
                                post.title,
                                style: TextStyle(
                                  fontSize: 16.sp,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w700,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),

                              SizedBox(height: 4.h),

                              // 详情文字
                              Text(
                                post.content,
                                style: TextStyle(
                                  fontSize: 12.sp,
                                  color: Colors.white,
                                  fontWeight: FontWeight.w400,
                                ),
                                maxLines: 3,
                                overflow: TextOverflow.ellipsis,
                              ),

                              Spacer(),

                              // 互动统计
                              Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: [
                                  // 评论数
                                  Image.asset(
                                    'assets/images/comment.png',
                                    width: 24.w,
                                    height: 24.w,
                                    fit: BoxFit.contain,
                                  ),
                                  SizedBox(width: 4.w),
                                  Text('$commentCount')
                                      .fontSize(10.sp)
                                      .textColor(Colors.white)
                                      .fontWeight(FontWeight.w700),
                                ],
                              ),
                              Spacer(),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                // 用户头像和用户名（右上角定位）
                Positioned(
                  top: 6.h,
                  right: 46.w,
                  child: Column(
                    children: [
                      Container(
                        width: 50.w,
                        height: 50.w,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10.r),
                          image: DecorationImage(
                            image: AssetImage(authorAvatar),
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      SizedBox(height: 4.h),
                      Text(authorNickname)
                          .fontSize(12.sp)
                          .textColor(Colors.white)
                          .fontWeight(FontWeight.w400),
                    ],
                  ).inkWell(
                    onTap: () {
                      // 跳转到用户详情页
                      controller.navigateToUserProfile(post.userId);
                    },
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
